package com.johann.leetcode;

public class T14_LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length<1) {
            return "";
        }
        if (1==strs.length) {
            return strs[0];
        }
        StringBuilder commonPre = new StringBuilder();
        //  0  hollyShit
        //  1  hole
        //  2  hollow
        //  3  holly
        //  4  ho
        // 以第一个元素的长度为 column
        // 以字符串数组的总长度为 row
        int column = strs[0].length();
        int row = strs.length;
        int flagIndex=-1;
        char c;
        //
        for (int j = 0; j < column; j++) {
            c=strs[0].charAt(j);
            for (int i = 0; i < row; i++) {
                // 在区间外
                if(j > strs[i].length()-1){
                       return flagIndex<0 ? "" : strs[0].substring(0,flagIndex);
                }else {
                    if (c != strs[i].charAt(j)) {
                       return flagIndex<0 ? "" : strs[0].substring(0,flagIndex);
                    }else {
                        flagIndex=j;
                    }
                }
            }
        }
        return flagIndex<0 ? "" : strs[0].substring(0,flagIndex+1);
    }

    public static void main(String[] args) {
        String [] strings = {"hh","hole","hollow","holly","holl"};
        System.out.printf(new T14_LongestCommonPrefix().longestCommonPrefix(strings));
    }
}
